<template>
  <div class="product-table-wrapper">
    <div class="page" v-for="(tableData, idx) in tableList" :key="idx">
      <div class="title">
        表 A.4{{ idx > 0 ? '（续）' : '' }} 产品数据一览表
      </div>

      <el-table :data="tableData" border :span-method="(params) => onMergeRow(params, idx)">
        <el-table-column prop="category" label="产品名称" align="center" />
        <el-table-column prop="count" label="购买量" align="center" />
        <el-table-column prop="color" label="规格" align="center" />
        <el-table-column prop="size" label="尺码" align="center" />
        <el-table-column prop="price" label="价格" align="center" />
      </el-table>
    </div>
  </div>
</template>

<script>
import _ from 'lodash';

export default {
  name: 'ProductTable',
  props: {
    data: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      rowIndexList: [],
      tableList: [],
    };
  },
  watch: {
    data: {
      handler() {
        this.init();
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    init() {
      const data = this.data.map(({ name, count, sku }) => {
        return sku.map((element) => ({ category: name, count, ...element, }));
      }).flat();
      this.tableList = _.chunk(data, 27);
      this.tableList.forEach((tableItem, index) => {
        const groupList = Object.values(_.groupBy(tableItem, 'category') || []);
        const indexArr = _.fill(Array(tableItem?.length), 0);
        groupList.forEach((item, idx) => {
          if (idx > 0) {
            const arr = _.cloneDeep(groupList).splice(0, idx).map((item) => item.length);
            const sum = arr.reduce((prev, curr) => prev + curr);
            indexArr[sum] = item.length;
          } else {
            indexArr[idx] = item.length;
          }
        });
        this.rowIndexList[index] = indexArr;
      });
    },
    onMergeRow({ columnIndex, rowIndex }, idx) {
      if ([0, 1].includes(columnIndex)) {
        if (this.rowIndexList[idx][rowIndex]) {
          return {
            rowspan: this.rowIndexList[idx][rowIndex],
            colspan: 1,
          };
        } else {
          return {
            rowspan: 0,
            colspan: 0,
          };
        }
      }
    },
  },
};
</script>
